package com.bawei.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.es.service.EsDocService;
import com.bawei.es.service.EsIndexService;
import com.bawei.system.domain.vo.EsDocInsertVo;
import com.bawei.system.domain.vo.EsDocQueryVo;
import com.bawei.system.domain.vo.EsDtoSelectVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EsDocServiceImpl implements EsDocService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private EsIndexService esIndexService;

    public static final String INDEX_NAME="add_index";

    @Override
    public R<Boolean> batchInsertDocs(List<EsDocInsertVo> esDocInsertVo) {
        BulkRequest request = new BulkRequest();
        esDocInsertVo.forEach(e -> {
            IndexRequest source = new IndexRequest(
                    e.getIndexName())
                    .source(e.getData(), XContentType.JSON);
            if (StringUtils.isNotEmpty(e.getId())) {
                source.id(e.getId());
            }
            request.add(source);
        });

        try {
            BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
            return R.ok(true, "插入成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.fail(false, "插入失败");
    }

    @Override
    public R queryDocs(EsDocQueryVo esDocInsertVo) {
        SearchRequest request = new SearchRequest(esDocInsertVo.getIndexName());
        //构建查询参数
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchAllQuery());
        //构建分页参数
        builder.from((esDocInsertVo.getPageVo().getCurrentPage() - 1) * esDocInsertVo.getPageVo().getPageSize());
        builder.size(esDocInsertVo.getPageVo().getPageSize());
        //构建排序参数
        try {
            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            log.info("查询结果：{}", JSONObject.toJSONString(search));
            SearchHit[] hits = search.getHits().getHits();
            List<Map<String,Object>> resultData = new ArrayList<>(hits.length);
            Arrays.stream(hits).forEach(h->{
                Map<String, Object> sourceAsMap = h.getSourceAsMap();
                resultData.add(sourceAsMap);
            });
        } catch (IOException e) {
            log.error("根据条件查询es数据失败：{}", e);
        }
        return null;
    }

    /**
     *  es删除
     * @param id
     */
    @Override
    public void deleteEsbyid(String id) {
        DeleteRequest deleteRequest = new DeleteRequest("add_index", id);
        try {
            DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 根据传入条件查询es的文档数据
    @Override
    public void querySuggestions(EsDtoSelectVo esDtoSelectVo) {
        if(esIndexService.indexCreate(INDEX_NAME).getData()){
            throw new RuntimeException("索引不存在");
        }
        SearchRequest request = new SearchRequest(esDtoSelectVo.getIndexName());
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestions",
                SuggestBuilders
                        .completionSuggestion(esDtoSelectVo.getSuggestFiles())
                        .prefix(esDtoSelectVo.getKeyWord())
                        .skipDuplicates (true)
                        .size(10)
        ));
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search( request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            String message = e.getMessage();
            if(message.contains("not")){
                message="es索引下的关键字不存在";
            }
            throw new RuntimeException(e);
        }
        Suggest suggest = response.getSuggest();
        List<String> list = new ArrayList<>();
        suggest.getSuggestion("suggestions").forEach(suggestion -> {
            suggestion.getOptions().forEach(entry -> {
                list.add(entry.getText().string());
            });
        });

    }

    @Override
    public R<List<Map>> selQueryDocs(EsDocQueryVo esDocInsertVo) {
//        if (StringUtils.isEmpty(esDocInsertVo.getKeyWord())){
//            throw new ServiceException("搜索参数不可以为空");
//        }
        // 若未查询到数量结果，直接进行返回
        List<Map> productInfoResponseList = new ArrayList<>();

        SearchRequest searchRequest = new SearchRequest(esDocInsertVo.getIndexName());
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        List<String> fields = esDocInsertVo.getSearchFields();
        String[] array = fields.toArray(new String[fields.size()]);
        // 商品名称搜索
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(
                esDocInsertVo.getKeyWord(), array);
        boolQueryBuilder.must(multiMatchQueryBuilder);
        // 分页
        searchSourceBuilder.from((esDocInsertVo.getPageVo().getCurrentPage() - 1) * esDocInsertVo.getPageVo().getPageSize());
        searchSourceBuilder.size(esDocInsertVo.getPageVo().getPageSize());

        searchSourceBuilder.query(boolQueryBuilder);

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        List<String> highlighFields = esDocInsertVo.getHighLightFields();
        if(CollectionUtils.isEmpty(highlighFields)){
            highlighFields=esDocInsertVo.getSearchFields();
        }
        for (String highligh : highlighFields) {
            highlightBuilder.field(highligh);
            highlightBuilder.preTags("<span style='color:red'>");
            highlightBuilder.postTags("</span>");
        }
        searchSourceBuilder.highlighter(highlightBuilder);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchResponseHits = searchResponse.getHits();
            TotalHits totalHits = searchResponseHits.getTotalHits();
            SearchHit[] searchHits = searchResponseHits.getHits();
            for (SearchHit searchHit : searchHits) {
                // 源数据
                String sourceAsString = searchHit.getSourceAsString();

                Map<String,Object> productInfoResponse =
                        com.alibaba.fastjson2.JSONObject.parseObject(sourceAsString, Map.class);
                // 高亮
                Map<String, HighlightField> highlightFields =
                        searchHit.getHighlightFields();
                for (String field : highlighFields) {
                    if (highlightFields != null){
                        HighlightField highlightField = highlightFields.get(field);
                        if (highlightField != null){
                            // 拼装
                            Text[] fragments = highlightField.getFragments();
                            StringBuilder sb = new StringBuilder();
                            for (Text fragment : fragments) {
                                sb.append(fragment);
                            }
                            productInfoResponse.put(field,sb.toString());
                        }
                    }
                }
                productInfoResponseList.add(productInfoResponse);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.ok(productInfoResponseList);
    }
}
